<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2018/1/30
 * Time: 下午10:32
 */

namespace common\logic;


use common\models\ReturnLogModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class ReturnLogLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return ReturnLogModel::find();
    }

    public function getSumByUid($uid)
    {
        $sum = $this->getSum('amount', ['uid' => $uid]);
        return empty($sum) ? 0 : $sum;
    }

    public function getSumByParentCode($code)
    {

        $where = ['like', 'parent_code', $code . '%', false];

        $users = UserLogic::instance()->getQuery($where, [], ['id'])->all();

        $userids = ArrayHelper::getColumn($users, 'id');

        $sum = $this->getSum('amount', ['uid' => $userids]);
        return empty($sum) ? 0 : $sum;
    }

    public function getSumByChildId($id){
        $sum = $this->getSum('amount', ['child_id' => $id]);
        return empty($sum) ? 0 : $sum;
    }


    public function getByPage($uid, $page, $pageSize = 20)
    {
        $nextPage = 0;
        $query = $this->_getActiveQuery();
        $queryNum = $this->_getActiveQuery();

        $offset = ($page - 1) * $pageSize;

        $tblLog = ReturnLogModel::tableName();
        $query = $query->where(["$tblLog.uid" => $uid])->limit($pageSize + 1)->joinWith('report')->offset($offset)->orderBy(["$tblLog.id" => SORT_DESC]);
        $queryNum = $queryNum->where(["$tblLog.uid" => $uid]);

        $data = $query->all();
        $dataNum = $queryNum->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }
        $result = [];

        $houseIds = ArrayHelper::getColumn($data,'report.house_id');

        $house = HouseLogic::instance()->getAll($houseIds);

        $house = ArrayHelper::map($house,'id','house_name');

        if (!empty($data)) {


            foreach ($data as $k => $v) {
                $result[] = [
                    'return_amount' => $v['amount'],
                    'return_time' => date('Y-m-d', $v['create_at']),
                    'house_name' => $house[$v['report']['house_id']],
                    'total_price' => $v['report']['sign_amount'],
                    'room' => $v['report']['sign_house']
                ];
            }

        }

        return ['nextPage' => $nextPage,'pageNum'=>count($dataNum), 'list' => $result];
    }
}